//------------------------------------------------------------------------------
//  <copyright file="ImageMatcher.cpp" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------
#include "ImageMatcher.h"

namespace Microsoft 
{
    namespace Robotics 
    {
        namespace Vision 
        {
			/// <summary>
			/// Initializes a new instance of the ImageMatcher class
			/// </summary>
			/// <param name="featureCount">The maximum number of features to find</param>
			/// <param name="ratio">The ratio between two points for them to be considered matched.  0 = Perfect match, 1 = Match with anything, suggested = 0.5</param>
			/// <param name="detector">The type of feature to detect, use values in SunflowerConstants.cs</param>
			/// <param name="culling">The type of culling to use, use values in SunflowerConstants.cs</param>
			ImageMatcher::ImageMatcher(int featureCount, float ratio, int detector, int culling)
			{
				// Create the simple matcher as a Sunflower feature matcher
				try
				{
					this->pMatcher = CreateSunflowerSimpleMatcher(NULL);
				}
				catch(Exception ^e)
				{
					throw gcnew Exception(e->Message);
				}

				// Define parameters of the feature detector for the database
				SunflowerSimpleMatcherParameters params;
				this->pMatcher->GetParameters(&params);
				params.detector_type = (DetectorType) detector;
				params.target_feature_count = featureCount;
				params.ratio_test_ratio = ratio;
				params.culling_type = (CullingType) culling;
				this->pMatcher->SetParameters(&params);
			}

			/// <summary>
			/// Adds an image to the KD tree loaded from a file
			/// </summary>
			/// <param name="filename">The name of the file to load</param>
			/// <param name="features">The found features</param>
			int ImageMatcher::AddImage(String ^filename, array<Feature> ^features)
			{
				array<wchar_t, 1> ^nativeFilename = filename->ToCharArray();
				pin_ptr<wchar_t> wideCharFilename = &(nativeFilename[0]);

				vt::CImg image;
				vt::VtLoadImage(wideCharFilename, image);
		
				return this->AddImage(image.BytePtr(), image.Width(), image.Height(), image.StrideBytes(), features);
			}

			/// <summary>
			/// Adds a grayscale image to the KD tree 
			/// </summary>
			/// <param name="grayImage">The grayscale image to add</param>
			/// <param name="width">width of the image</param>
			/// <param name="height">height of the image</param>
			/// <param name="stride">stride, in bytes, of one row of the image</param>
			int ImageMatcher::AddImage(BYTE *img, int width, int height, int stride, array<Feature> ^features)
			{
				SF_BYTE_IMAGE rgbImage = SF_BYTE_IMAGE(width, height, stride, img);

				this->pMatcher->AddImage(rgbImage);
				this->numImages++;

				const FeaturePoint *foundFeatures = this->pMatcher->GetFeatures(this->numImages - 1);
				for(int i = 0; i < this->pMatcher->GetFeatureCount(this->numImages - 1); i++)
				{
					features[i].X = foundFeatures[i].x;
					features[i].Y = foundFeatures[i].y;
				}

				return this->pMatcher->GetFeatureCount(this->numImages - 1);
			}

			/// <summary>
			/// Matches an image loaded from a file
			/// </summary>
			/// <param name="filename">Name of the file to load</param>
			/// <param name="features">The features found in the query image</param>
			/// <param name="matchedFeatures">The matched features</param>
			int ImageMatcher::MatchImage(String ^filename, array<Feature> ^features, array<MatchedFeatures> ^matchedFeatures)
			{
				array<wchar_t, 1> ^nativeFilename = filename->ToCharArray();
				pin_ptr<wchar_t> wideCharFilename = &(nativeFilename[0]);

				vt::CImg image;
				vt::VtLoadImage(wideCharFilename, image);

				return this->MatchImage(image.BytePtr(), image.Width(), image.Height(), image.StrideBytes(), features, matchedFeatures);
			}

			/// <summary>
			/// Matches an image
			/// </summary>
			/// <param name="grayImage">The grayscale image to add</param>
			/// <param name="width">width of the image</param>
			/// <param name="height">height of the image</param>
			/// <param name="stride">stride, in bytes, of one row of the image</param>
			/// <param name="features">The features found in the query image</param>
			/// <param name="matchedFeatures">The matched features</param>
			int ImageMatcher::MatchImage(BYTE *img, int width, int height, int stride, array<Feature> ^features, array<MatchedFeatures> ^matchedFeatures)
			{
				// Convert to sunflower data types
				SF_BYTE_IMAGE rgbImage = SF_BYTE_IMAGE(width, height, stride, img);

				// Find matches for all images
				this->pMatcher->Match(rgbImage);
				
				// Find the most likely image (one with the most matches)
				int max = -1;
				int index = 0;

				for(int i = 0; i < this->pMatcher->GetImageCount(); i++)
				{
					if(this->pMatcher->GetMatchCount(i) > max)
					{
						max = this->pMatcher->GetMatchCount(i);
						index = i;
					}
				}

				this->mostLikelyImage = index;

				// Get the feature id of the matched feature in the most likely image
				SF_FEATURE_MATCH *matches = this->pMatcher->GetMatches();
				
				int featureCount = this->pMatcher->GetMatchImageFeatureCount();
				int matchCount = 0;

				//Get the list of matched features
				const FeaturePoint *foundFeatures = this->pMatcher->GetMatchImageFeatures();
				
				for(int i = 0; i < this->pMatcher->GetMatchImageFeatureCount(); i++)
				{
					features[i].X = foundFeatures[i].x;	
					features[i].Y = foundFeatures[i].y;
					features[i].Sxx = foundFeatures[i].sxx;
					features[i].Syy = foundFeatures[i].syy;
					features[i].Sxy = foundFeatures[i].sxy;
					features[i].Score = foundFeatures[i].score;
				}
				
				for(int i = 0, j = 0; i < this->pMatcher->GetMatchCount() && j < matchedFeatures->Length; i++)
				{
					if(matches[i].image2 == index || matches[i].image1 == index)
					{
						matchedFeatures[j].DatabaseFeatureId = matches[i].feature2;
						matchedFeatures[j].QueryImageFeatureId = matches[i].feature1;
						matchedFeatures[j].MostLikelyImage = index;
						matchCount++;
						j++;
					}
				}

				// return the number of matched features
				return matchCount;
			}
		}
	}
}
